import * as THREE from 'three';

import {
    OrbitControls
} from 'three/addons/controls/OrbitControls.js';
import {
    DRACOLoader
} from 'three/addons/loaders/DRACOLoader.js';
import {
    GLTFLoader
} from 'three/addons/loaders/GLTFLoader.js';
// import * as TWEEN from "/assets/tweenjs.min.js"
console.log(THREE);
(function () {
    console.log("炉膛温度场文件");
    let now_open_diag = {}
    let fireStateFlag = false;
    now_open_diag.API_URL = ' '
    //创建一个三维场景
    document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    const devicePixelRatio = window.devicePixelRatio; //设备分辨率
    function Request(baseUrl = '', time = 1000) {
        this.baseUrl = baseUrl;

        function request(url, option = {}) {
            return new Promise(async (resolve, reject) => {
                try {
                    const response = await fetch(baseUrl + url, option);
                    if (response.status == '200') {
                        const data = await response.json();
                        if (data.code == '200') {
                            resolve(data);
                        } else {
                            reject(data.message || '请求失败');
                        }
                    } else {
                        reject(response);
                    }
                } catch (e) {
                    reject(e);
                }
            })
        }

        this.post = function (url, data) {
            return request(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
        }

        this.get = function (url) {
            return request(url, {
                method: 'GET'
            })
        }
    }

    let runcaizhi = ""
    let stopcaizhi = ""
    Request.createRequest = function (baseUrl) {
        return new Request(baseUrl);
    }
    const request = Request.createRequest(now_open_diag.API_URL);
    
    let scene, light, spotLight, renderer, controls, camera, mesh
    let krq1 = new THREE.Object3D(); //初始化一个空容器，装载粒子
    let krq2 = new THREE.Object3D();
    krq2.name = '火焰例子'
    let krq3 = new THREE.Object3D();
    let krq4 = new THREE.Object3D();
    let krq5 = new THREE.Object3D();
    let krq6 = new THREE.Object3D();
    let krq7 = new THREE.Object3D();
    let krq8 = new THREE.Object3D();
    let krq9 = new THREE.Object3D();
    let krq10 = new THREE.Object3D();
    let krq11 = new THREE.Object3D();
    let krq12 = new THREE.Object3D();
    let krq13 = new THREE.Object3D();
    let krq14 = new THREE.Object3D();
    let krq15 = new THREE.Object3D();
    let krq16 = new THREE.Object3D();
    let krq17 = new THREE.Object3D();
    let krq18 = new THREE.Object3D();
    let krq19 = new THREE.Object3D();
    let krq20 = new THREE.Object3D();
    let krq21 = new THREE.Object3D();
    let krq22 = new THREE.Object3D();
    let krq23 = new THREE.Object3D();
    let krq24 = new THREE.Object3D();

     
    //初始化场景元素
    const initCanvas = () => {
        initScene()
        initLight()
        initCamera()
        //initASphere()
        initSceneItems()
        initARenderer()
        initAControls()
    }

    const initScene = () => {
        scene = new THREE.Scene()
        // 场景设置
        //scene.background = new THREE.Color('#03244a')
        //在代码上面声明场景等下面加这句:
        scene.fog = new THREE.Fog('#333', 120, 150)
        //创建辅助坐标轴
        // const axesHelper = new THREE.AxesHelper(100)
        // scene.add(axesHelper)
        //加个地板 投射影子
        // let floorGeometry = new THREE.PlaneGeometry(50, 50,32, 32) //形状
        // let floorMaterial =new THREE.MeshStandardMaterial( {color: 0x03244a} );//材质
        // let floor = new THREE.Mesh(floorGeometry, floorMaterial)
        // floor.rotation.x = -0.5 * Math.PI
        // floor.receiveShadow = true
        // floor.position.y = -0.001
        // scene.add(floor)
    }

    //创建灯光
    const initLight = () => {
        // const ambient = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.05 );
        light = new THREE.AmbientLight(0xffffff, 0.5); // soft white light
        scene.add(light);
        // 聚光灯
        spotLight = new THREE.SpotLight(0xffffff, 5);
        spotLight.position.set(25, 150, 75);
        spotLight.angle = Math.PI / 6;
        spotLight.penumbra = 1;
        spotLight.decay = 2;
        spotLight.distance = 300;
        // spotLight.map = textures[ 'disturb.jpg' ];
        spotLight.castShadow = true; //可以产生阴影
        spotLight.shadow.mapSize.width = 2048;
        spotLight.shadow.mapSize.height = 2048;
        spotLight.shadow.camera.near = 10;
        spotLight.shadow.camera.far = 200;
        spotLight.shadow.focus = 1;
        scene.add(spotLight);
    }

    //创建相机
    const initCamera = () => {
        //创建一个透视相机
        const width = document.getElementById('three').offsetWidth
        const height = document.getElementById('three').offsetHeight
        // console.log(width);
        camera = new THREE.PerspectiveCamera(80, width / height, 1, 3000)
        //设置相机位置
        //x 轴红色  y绿色  z  蓝色
        camera.position.set(0, 0, 12)
        // camera.position.set(200, 200, 200);
        // camera.layers.disableAll();
        // camera.layers.enableAll();
        // camera.layers.disable( 1);
        // camera.layers.enable( 1);
        //设置相机方向
        // camera.lookAt(0,-5,0)
        //创建助手
        // const helper = new THREE.CameraHelper( spotLight.shadow.camera );
        // scene.add( helper );
    }

    //创建场景元素
    const initSceneItems = () => {
        sessionStorage.setItem('glnumber', 4)
        const gltfLoader2 = new GLTFLoader();
        var dracoLoader = new DRACOLoader();
        // dracoLoader.setDecoderPath( '/js/draco/' );
        dracoLoader.setDecoderPath('/examples/js/libs/draco/');
        // 定义着色器代码
        const vertexShader = `
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;

        const fragmentShader = `
        uniform float time;
        varying vec2 vUv;
        void main() {
          vec3 color = vec3(1.0, 0.5, 0.0); // 火焰颜色
           gl_FragColor = vec4(color,1.0);
        }
        `;
        // float noise = abs(fract(sin(dot(gl_FragCoord.xyz + time, vec3(12.9898, 78.233, 45.5432))) * 42758.5453));
        // gl_FragColor = vec4(color * noise, 1.0);

        // 创建材质

        const material = new THREE.ShaderMaterial({
            uniforms: {
                time: { value: 0 }
            },
            vertexShader,
            fragmentShader
        });
        gltfLoader2.setDRACOLoader(dracoLoader);
        const url2 = './guolu.glb';
        gltfLoader2.load(url2, (gltf) => {
            const root = gltf.scene;
            console.log(root.children);
            // 给每个mesh 添加阴影
            root.traverse(function (node) {
                if (node instanceof THREE.Mesh) {
                    node.castShadow = true;
                }
            });
            mesh = root
            //纹理贴图加载器TextureLoader
            // .load()方法加载图像，返回一个纹理对象Texture
            runcaizhi = material
            stopcaizhi = mesh.children[7].material
            // mesh.children[4].material.map=texture
            // mesh.children[4].material.opacity = 0.4
            // mesh.children[4].material.transparent = true
            // mesh.children[5].material.transparent = true
            // mesh.children[0].material.transparent = true
            // mesh.children[3].material.transparent = true
            // mesh.children[1].material.transparent = true
            // mesh.children[2].material.transparent = true
            mesh.children[7].material.opacity = 0.3
            mesh.children[7].material.opacity = mesh.children[8].material.opacity
            mesh.children[23].visible = false
            mesh.children[0].position.y = -2
            mesh.children[9].position.y = -1.2
            mesh.children[16].position.y = -1.2
            mesh.children[23].position.y = -1.2
            // mesh.children[1].material.opacity = 0.3
            // 6-11 为 soft E D C B A
            // mesh.children[5].geometry =
            // mesh.children[6].material = materiali
            mesh.children[7].material = material
            // mesh.children[8].visible = false
            // mesh.children[9].material = materiali
            // mesh.children[10].material = materiali
            // mesh.children[11].material = materiali
            // mesh.children[12].material = materiali
            // mesh.children[13].material = materiali
            // mesh.children[18].visible = false
            mesh.position.y = -5
            mesh.position.x = 0
            mesh.position.z = 0
            mesh.rotation.y = 0
            mesh.castShadow = true; //有阴影
            // mesh.scale.set(0.2,0.2,0.2);
            console.log(mesh.children[7].material)
            scene.add(mesh);
            // function animate() {
            //     requestAnimationFrame(animate);
            //     material.uniforms.time.value += 0.1;
            //     renderer.render(scene, camera);
            // }
            // animate();
            if (sessionStorage.getItem('glnumber') == 4) {
                mesh.children[1].visible = mesh.children[10].visible = mesh.children[17].visible = mesh.children[24].visible = false
                mesh.children[2].visible = mesh.children[11].visible = mesh.children[18].visible = mesh.children[25].visible = false

            } else if (sessionStorage.getItem('glnumber') == 5) {
                mesh.children[1].visible = mesh.children[10].visible = mesh.children[17].visible = mesh.children[24].visible = false

            }

            // initFireSpite()
            initFlame()
            for (let j = 3; j < mesh.parent.children.length; j++) {
                mesh.parent.children[j].visible = false
            }


        },
            // 加载过程回调函数onProgress：加载过程不停地重复执行该函数中代码
            function (xhr) {
                // 控制台查看加载进度xhr
                // 通过加载进度xhr可以控制前端进度条进度   Math.floor:小数加载进度取整
                //console.log('加载进度' + Math.floor(xhr.loaded / xhr.total * 100) + '%');
            },
            // 加载错误回调函数onError
            function (err) {
                console.error('加载发生错误');
            }
        );
    }

    // 创建精灵 火焰效果
    const initFireSpite = () => {
        var map = new THREE.TextureLoader().load("./assets/flamex.png");
        var material = new THREE.SpriteMaterial({
            map: map,
            color: 0xffffff,
            fog: true
        });

        var sprite = new THREE.Sprite(material);
        sprite.position.y = -3
        sprite.position.x = -0.5
        sprite.rotation.x = 180

        scene.add(sprite);
    }


    function initFlame() {
        var texture = new THREE.TextureLoader().load("./assets/flamex.png");
        // var texture1 = new THREE.TextureLoader().load("./assets/flamex1.png");
        // var texture2 = new THREE.TextureLoader().load("./assets/flamex2.png");
        //sprite材质
        var material = new THREE.SpriteMaterial({
            //以canvas作为纹理
            map: texture,
            //混合度 减法混合
            blending: THREE.AdditiveBlending,
            color: 0xffffff,
            fog: true
        });

        // var material1 = new THREE.SpriteMaterial({
        //     //以canvas作为纹理
        //     map: texture1,
        //     //混合度 加法混合
        //     blending: THREE.AdditiveBlending
        // });var material2 = new THREE.SpriteMaterial({
        //     //以canvas作为纹理
        //     map: texture2,
        //     //混合度 加法混合
        //     blending: THREE.AdditiveBlending
        // });
        //循环1000  添加粒子
        for (var i = 0; i < 800; i++) {
            var particle = new THREE.Sprite(material);
            var particle1 = new THREE.Sprite(material);
            var particle2 = new THREE.Sprite(material);
            var particle3 = new THREE.Sprite(material);

            var particle4 = new THREE.Sprite(material);
            var particle5 = new THREE.Sprite(material);
            var particle6 = new THREE.Sprite(material);
            var particle7 = new THREE.Sprite(material);

            var particle8 = new THREE.Sprite(material);
            var particle9 = new THREE.Sprite(material);
            var particle10 = new THREE.Sprite(material);
            var particle11 = new THREE.Sprite(material);

            var particle12 = new THREE.Sprite(material);
            var particle13 = new THREE.Sprite(material);
            var particle14 = new THREE.Sprite(material);
            var particle15 = new THREE.Sprite(material);

            // var particle16 = new THREE.Sprite(material);
            // var particle17 = new THREE.Sprite(material);
            // var particle18 = new THREE.Sprite(material);
            // var particle19 = new THREE.Sprite(material);

            // var particle20 = new THREE.Sprite(material);
            // var particle21 = new THREE.Sprite(material);
            // var particle22 = new THREE.Sprite(material);
            // var particle23 = new THREE.Sprite(material);


            initParticle(particle, i);
            initParticle(particle1, i);
            initParticle(particle2, i);
            initParticle(particle3, i);

            initParticle(particle4, i);
            initParticle(particle5, i);
            initParticle(particle6, i);
            initParticle(particle7, i);

            initParticle(particle8, i);
            initParticle(particle9, i);
            initParticle(particle10, i);
            initParticle(particle11, i);

            initParticle(particle12, i);
            initParticle(particle13, i);
            initParticle(particle14, i);
            initParticle(particle15, i);

            // initParticle(particle16, i);
            // initParticle(particle17, i);
            // initParticle(particle18, i);
            // initParticle(particle19, i);

            // initParticle(particle20, i);
            // initParticle(particle21, i);
            // initParticle(particle22, i);
            // initParticle(particle23, i);


            krq4.add(particle);
            krq4.name = "particles_flame";
            krq2.add(particle1);
            krq2.name = "particles_flame1";
            krq3.add(particle2);
            krq3.name = "particles_flame2";
            krq1.add(particle3);
            krq1.name = "particles_flame3";

            krq5.add(particle7);
            krq5.name = "particles_flame4";
            krq6.add(particle5);
            krq6.name = "particles_flame5";
            krq7.add(particle6);
            krq7.name = "particles_flame6";
            krq8.add(particle4);
            krq8.name = "particles_flame7";

            krq9.add(particle11);
            krq9.name = "particles_flame8";
            krq10.add(particle9);
            krq10.name = "particles_flame9";
            krq11.add(particle10);
            krq11.name = "particles_flame10";
            krq12.add(particle8);
            krq12.name = "particles_flame11";

            krq13.add(particle15);
            krq13.name = "particles_flame12";
            krq14.add(particle13);
            krq14.name = "particles_flame13";
            krq15.add(particle14);
            krq15.name = "particles_flame14";
            krq16.add(particle12);
            krq16.name = "particles_flame15";

            // krq17.add(particle16);
            // krq17.name = "particles_flame16";
            // krq18.add(particle17);
            // krq18.name = "particles_flame17";
            // krq19.add(particle18);
            // krq19.name = "particles_flame18";
            // krq20.add(particle19);
            // krq20.name = "particles_flame19";

            // krq21.add(particle20);
            // krq21.name = "particles_flame20";
            // krq22.add(particle21);
            // krq22.name = "particles_flame21";
            // krq23.add(particle22);
            // krq23.name = "particles_flame22";
            // krq24.add(particle23);
            // krq24.name = "particles_flame23";
        }
        // krq.position.set(1, -3.6, -1);
        // A层火焰
        krq3.position.set(0.95, -6, -0.9);
        krq3.rotation.set(0, 0.36, 1);
        krq3.scale.set(0.3, 0.25, 0.2);;
        krq3.scale.multiplyScalar(1);
        // 2
        krq2.position.set(-0.99, -6, -1);
        krq2.rotation.set(0, -10.56, 1);
        krq2.scale.set(0.3, 0.25, 0.2);;
        krq2.scale.multiplyScalar(1);
        // 3
        krq1.position.set(-0.93, -6, 1);
        krq1.rotation.set(0, 3.75, 1);
        krq1.scale.set(0.3, 0.25, 0.2);;
        krq1.scale.multiplyScalar(1);
        // 4
        krq4.position.set(1, -6, 1);
        krq4.rotation.set(0, -0.8, 1);
        krq4.scale.set(0.3, 0.25, 0.2);;
        krq4.scale.multiplyScalar(1);

        // // B层火焰5
        krq7.position.set(0.95, -5.75, -0.9);
        krq7.rotation.set(0, 0.36, 1);
        krq7.scale.set(0.3, 0.25, 0.2);;
        krq7.scale.multiplyScalar(1);
        // 6
        krq6.position.set(-0.99, -5.75, -1);
        krq6.rotation.set(0, -10.56, 1);
        krq6.scale.set(0.3, 0.25, 0.2);;
        krq6.scale.multiplyScalar(1);
        // 7
        krq5.position.set(-0.93, -5.75, 1);
        krq5.rotation.set(0, 3.75, 1);
        krq5.scale.set(0.3, 0.25, 0.2);;
        krq5.scale.multiplyScalar(1);
        // 8
        krq8.position.set(1, -5.75, 1);
        krq8.rotation.set(0, -0.8, 1);
        krq8.scale.set(0.3, 0.25, 0.2);;
        krq8.scale.multiplyScalar(1);
        // c层火焰9
        krq11.position.set(0.95, -5.45, -0.9);
        krq11.rotation.set(0, 0.36, 1);
        krq11.scale.set(0.3, 0.25, 0.2);
        krq11.scale.multiplyScalar(1);
        // 10
        krq10.position.set(-0.99, -5.45, -1);
        krq10.rotation.set(0, -10.56, 1);
        krq10.scale.set(0.3, 0.25, 0.2);;
        krq10.scale.multiplyScalar(1);
        // 11
        krq9.position.set(-0.93, -5.45, 1);
        krq9.rotation.set(0, 3.75, 1);
        krq9.scale.set(0.3, 0.25, 0.2);;
        krq9.scale.multiplyScalar(1);
        // 12
        krq12.position.set(1, -5.45, 1);
        krq12.rotation.set(0, -0.8, 1);
        krq12.scale.set(0.3, 0.25, 0.2);;
        krq12.scale.multiplyScalar(1);
        // // D层火焰 13
        krq15.position.set(0.95, -5.15, -0.9);
        krq15.rotation.set(0, 0.36, 1);
        krq15.scale.set(0.3, 0.25, 0.2);;
        krq15.scale.multiplyScalar(1);
        // 14
        krq14.position.set(-0.99, -5.15, -1);
        krq14.rotation.set(0, -10.56, 1);
        krq14.scale.set(0.3, 0.25, 0.2);;
        krq14.scale.multiplyScalar(1);
        // 15
        krq13.position.set(-0.93, -5.15, 1);
        krq13.rotation.set(0, 3.75, 1);
        krq13.scale.set(0.3, 0.25, 0.2);
        krq13.scale.multiplyScalar(1);
        // 16
        krq16.position.set(1, -5.15, 1);
        krq16.rotation.set(0, -0.8, 1);
        krq16.scale.set(0.3, 0.25, 0.2);;
        krq16.scale.multiplyScalar(1);
        // // E层火焰17
        // krq17.position.set(0.95, -4.9, -0.9);
        // krq17.rotation.set(0, 0.36, 1);
        // krq17.scale.set(0.3, 0.25, 0.2);;
        // krq17.scale.multiplyScalar(1);
        // // 18
        // krq18.position.set(-0.99, -4.9, -1);
        // krq18.rotation.set(0, -10.56, 1);
        // krq18.scale.set(0.3, 0.25, 0.2);;
        // krq18.scale.multiplyScalar(1);
        // // 19
        // krq19.position.set(-0.93, -4.9, 1);
        // krq19.rotation.set(0, 3.75, 1);
        // krq19.scale.set(0.3, 0.25, 0.2);;
        // krq19.scale.multiplyScalar(1);
        // // 20
        // krq20.position.set(1, -4.9, 1);
        // krq20.rotation.set(0, -0.8, 1);
        // krq20.scale.set(0.3, 0.25, 0.2);;
        // krq20.scale.multiplyScalar(1);
        // // F层火焰21
        // krq21.position.set(0.95, -4.7, -0.9);
        // krq21.rotation.set(0, 0.36, 1);
        // krq21.scale.set(0.3, 0.25, 0.2);
        // krq21.scale.multiplyScalar(1);
        // // 22
        // krq22.position.set(-0.99, -4.7, -1);
        // krq22.rotation.set(0, -10.56, 1);
        // krq22.scale.set(0.3, 0.25, 0.2);
        // krq22.scale.multiplyScalar(1);
        // // 23
        // krq23.position.set(-0.93, -4.7, 1);
        // krq23.rotation.set(0, 3.75, 1);
        // krq23.scale.set(0.3, 0.25, 0.2);
        // krq23.scale.multiplyScalar(1);
        // // // 24
        // krq24.position.set(1, -4.7, 1);
        // krq24.rotation.set(0, -0.8, 1);
        // krq24.scale.set(0.3, 0.25, 0.2);
        // krq24.scale.multiplyScalar(1);


        // if (sessionStorage.getItem('glnumber') == 4) {
        scene.add(krq1, krq2, krq3, krq4)
        scene.add(krq5, krq6, krq7, krq8)
        scene.add(krq9, krq10, krq11, krq12)
        scene.add(krq13, krq14, krq15, krq16)
        // } else if (sessionStorage.getItem('glnumber') == 5) {
        //     scene.add(krq1, krq2, krq3, krq4);
        //     scene.add(krq5, krq6, krq7, krq8)
        //     scene.add(krq9, krq10, krq11, krq12)
        //     scene.add(krq13, krq14, krq15, krq16)
        //     scene.add(krq17, krq18, krq19, krq20)

        // } else if (sessionStorage.getItem('glnumber') == 6) {
        //     scene.add(krq1, krq2, krq3, krq4);
        //     scene.add(krq5, krq6, krq7, krq8)
        //     scene.add(krq9, krq10, krq11, krq12)
        //     scene.add(krq13, krq14, krq15, krq16)
        //     scene.add(krq17, krq18, krq19, krq20)
        //     scene.add(krq21, krq22, krq23, krq24)
        // }
    }

    /**
     * 粒子 延迟发散
     * @param particle
     * @param delay
     */
    
    function initParticle(particle, delay) {
        particle.position.set(5, Math.random() + 5, 0);
        particle.scale.x = particle.scale.y = Math.random() * 3;
        //下面是一系列的动画
        var xx = Math.random() * 10 - 5;
        var yy = Math.cos((Math.PI / 100) * xx) * 21;
        //位移
        // debugger
        new TWEEN.Tween(particle.position)
            .delay(delay)
            .to({
                x: xx,
                y: yy,
                z: Math.random() * 10 - 5
            }, 2000)
            .onComplete(function () {
                initParticle(particle, delay);
            })
            .start();
        // 大小
        new TWEEN.Tween(particle.scale)
            .delay(delay)
            .to({
                x: 0.01,
                y: 0.01
            }, 900)
            .start();
    }
    
    //创建渲染
    const initARenderer = () => {
        renderer = new THREE.WebGLRenderer({
            antialias: true,
            logarithmicDepthBuffer: true,
            alpha: true,
        });
        // renderer.setPixelRatio (devicePixelRatio)
        renderer.setPixelRatio(window.devicePixelRatio);
        // console.log(document.getElementById('three').offsetWidth);
        renderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight);
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        // renderer.outputEncoding = THREE.sRGBEncoding;
    }

    const render = () => {
        // console.log(renderer);
        renderer.render(scene, camera)
        // labelRenderer.render( scene, camera )
        controls.update();
        TWEEN.update();
        requestAnimationFrame(render);
    }

    window.addEventListener('resize', onWindowResize);

    function onWindowResize() {
        camera.aspect = document.getElementById('three').offsetWidth / document.getElementById('three').offsetHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight);
        // labelRenderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight );
        // labelRenderer.render( scene, camera )
        // renderer.render(scene, camera)

    }

    //创建相机控制器
    const initAControls = () => {
        // controls.enableDamping = true
        // 设置阻尼

        //controls = new TrackballControls(camera, document.querySelector('#three'));
        // controls.noZoom = true;
        //console.log(controls);
        //controls.noPan = true;
        // controls.handleResize();
        controls = new OrbitControls(camera, document.querySelector('#three'))
        //controls = new OrbitControls(camera, renderer.domElement)
        controls.update();
        controls.autoRotate = true
        // controls.enableDamping = true;
        controls.autoRotateSpeed = 1;
        // controls.enableRotate=false
        // controls.enablePan=false  //右键平移
        //
        // controls.maxAzimuthAngle=0
        // controls.minAzimuthAngle=0
        // controls.maxPolarAngle = 1
        // controls.minPolarAngle = 1
        controls.target.set(0, -2, 0);
        // controls.addEventListener('change',()=>{
        //   console.log('change');
        //   renderer.render(scene, camera)
        // // labelRenderer.render( scene, camera )
        //
        // })
    }

    initCanvas()
    // console.log(renderer.domElement);
    document.getElementById('three')?.appendChild(renderer.domElement)
    render()

    const initEvent = (str, isb) => { //    
        //获取事件元素
        let oFootBtns = document.getElementById(str).children //底部菜单 btns
        if (str == "zbf_foot_btns") {
            now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 1].style.display = "none"
            // now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 2].style.display = "none"
        }
        for (let i = 0; i < oFootBtns.length; i++) {
            oFootBtns[i].onclick = () => {
                if (isb) {
                    for (let ii = 0; ii < oFootBtns.length; ii++) {
                        oFootBtns[ii].className = ""
                    }
                    oFootBtns[i].className = "active"
                } else {
                    if (i != 6) {
                        oFootBtns[i].className = oFootBtns[i].className == "active" ? "" : "active"
                    }
                }

                if (str == "zbf_r_btns") {
                    if (i == 6) {
                        for (let huo = 0; huo < scene.children.length; huo++) {
                            if (huo >= 3) {
                                scene.children[huo].visible = false
                            }
                        }
                        // A层
                        console.log(scene)
                        scene.children[2].children[6].visible = false
                        scene.children[2].children[15].visible = false
                        scene.children[2].children[29].visible = false
                        scene.children[2].children[22].visible = false
                        // B层
                        scene.children[2].children[5].visible = false
                        scene.children[2].children[14].visible = false
                        scene.children[2].children[21].visible = false
                        scene.children[2].children[28].visible = false
                        // c层
                        scene.children[2].children[4].visible = false
                        scene.children[2].children[13].visible = false
                        scene.children[2].children[20].visible = false
                        scene.children[2].children[27].visible = false
                        // 控制D层显隐藏
                        scene.children[2].children[3].visible = false
                        scene.children[2].children[12].visible = false
                        scene.children[2].children[19].visible = false
                        scene.children[2].children[26].visible = false
                        // 燃尽风
                        scene.children[2].children[0].visible = false
                        scene.children[2].children[9].visible = false
                        scene.children[2].children[16].visible = false
                        scene.children[2].children[23].visible = false

                        for (let ii = 0; ii < oFootBtns.length; ii++) {
                            oFootBtns[ii].className = ""
                        }
                    } else if (i == 0) {
                        // 控制A层显隐藏
                        scene.children[2].children[6].visible = !scene.children[2].children[6].visible
                        scene.children[2].children[15].visible = !scene.children[2].children[15].visible
                        scene.children[2].children[29].visible = !scene.children[2].children[29].visible
                        scene.children[2].children[22].visible = !scene.children[2].children[22].visible
                        // for (let ahuo = 4; ahuo <= 7; ahuo++) {
                        //     scene.children[ahuo].visible = !scene.children[ahuo].visible
                        // }
                        // scene.children[2].children[6].visible = scene.children[2].children[12].visible = !scene.children[2].children[6].visible

                    } else if (i == 1) {
                        // 控制B层显隐藏
                        scene.children[2].children[5].visible = !scene.children[2].children[5].visible
                        scene.children[2].children[14].visible = !scene.children[2].children[14].visible
                        scene.children[2].children[21].visible = !scene.children[2].children[21].visible
                        scene.children[2].children[28].visible = !scene.children[2].children[28].visible
                        // for (let ahuo = 8; ahuo <= 11; ahuo++) {
                        //     scene.children[ahuo].visible = !scene.children[ahuo].visible
                        // }
                    } else if (i == 2) {
                        // 控制C层显隐藏
                        scene.children[2].children[4].visible = !scene.children[2].children[4].visible
                        scene.children[2].children[13].visible = !scene.children[2].children[13].visible
                        scene.children[2].children[20].visible = !scene.children[2].children[20].visible
                        scene.children[2].children[27].visible = !scene.children[2].children[27].visible
                        // for (let ahuo = 12; ahuo <= 15; ahuo++) {
                        //     scene.children[ahuo].visible = !scene.children[ahuo].visible
                        // }
                    } else if (i == 3) {
                        // 控制D层显隐藏
                        scene.children[2].children[3].visible = !scene.children[2].children[3].visible
                        scene.children[2].children[12].visible = !scene.children[2].children[12].visible
                        scene.children[2].children[19].visible = !scene.children[2].children[19].visible
                        scene.children[2].children[26].visible = !scene.children[2].children[26].visible

                    }

                    else if (i == 4) {
                        //  燃尽风显隐藏
                        scene.children[2].children[0].visible = !scene.children[2].children[0].visible
                        scene.children[2].children[9].visible = !scene.children[2].children[9].visible
                        scene.children[2].children[16].visible = !scene.children[2].children[16].visible
                        // scene.children[2].children[23].visible = !scene.children[2].children[23].visible

                    } else if (i == 5) {
                        fireStateFlag = !fireStateFlag;
                        //  火焰状态true
                        document.getElementById('zbf_r_btns').addEventListener("click", function () {
                            const databox = []
                            request.get('/api/sjdl/home/dcs/zs').then(res => {
                                // let res = {
                                //     code: 200,
                                //     data: {
                                //         D1: 572.4484566697683,
                                //         C1: 854.1832947776439,
                                //         D2: 898.4317159396564,
                                //         B1: 687.1815219576139,
                                //         C2: 478.12991366890276,
                                //         D3: 391.1707693675136,
                                //         A1: 1,
                                //         B2: 215.81176201718466,
                                //         C3: 857.114027037535,
                                //         D4: 888.1154598998936,
                                //         A2: 1,
                                //         B3: 450.2514783081176,
                                //         C4: 231.766571615474,
                                //         A3: 0,
                                //         B4: 990.7000009157425,
                                //         A4: 518.9111773994057
                                //     },
                                //     message: "获取数据成功"
                                // }
                                for (let k in res.data) { databox.push({ [k]: res.data[k] }) }
                                databox.sort((a, b) => {
                                    let aKey = Object.keys(a)[0];
                                    let bKey = Object.keys(b)[0];
                                    if (aKey[0] === bKey[0]) {
                                        return aKey.slice(1) - bKey.slice(1);
                                    } else {
                                        return aKey[0].charCodeAt() - bKey[0].charCodeAt();
                                    }
                                });
                                // console.log(databox,scene.children)

                                databox.forEach(obj => {
                                    let key = Object.keys(obj)[0];
                                    let value = obj[key].toFixed(2);
                                })
                                if (document.getElementById('zbf_r_btns').children[5].className == "") {
                                    for (let ahuo = 3; ahuo <= 18; ahuo++) {
                                        scene.children[ahuo].visible = false
                                    }
                                } else {
                                    databox.forEach((obj, index) => {
                                        Object.keys(obj).forEach((key) => {
                                            let value = obj[key];
                                            if (value !== 0) {
                                                scene.children[index + 3].visible = true
                                            } else {
                                                console.log(index + 3)
                                                scene.children[index + 3].visible = false
                                            }
                                        });
                                    });
                                }
                            })

                            // request.post('/spf/visit/getThermalFieldAll').then(res => {

                            //     rsqState[0] = res.data.runStateA
                            //     rsqState[1] = res.data.runStateB
                            //     rsqState[2] = res.data.runStateC
                            //     rsqState[3] = res.data.runStateD
                            //     if (document.getElementById('zbf_r_btns').children[5].className == "") {
                            //         for (let ahuo = 3; ahuo <= 18; ahuo++) {
                            //             scene.children[ahuo].visible = false
                            //         }
                            //     } else {
                            //         if (rsqState[0] == 1) {
                            //             scene.children[3].visible = false
                            //             scene.children[4].visible = false
                            //             scene.children[5].visible = false
                            //             scene.children[6].visible = false
                            //         } else {
                            //             scene.children[3].visible = true
                            //             scene.children[4].visible = true
                            //             scene.children[5].visible = true
                            //             scene.children[6].visible = true
                            //         }
                            //         if (rsqState[1] == 1) {
                            //             scene.children[7].visible = false
                            //             scene.children[8].visible = false
                            //             scene.children[9].visible = false
                            //             scene.children[10].visible = false

                            //         } else {
                            //             scene.children[7].visible = true
                            //             scene.children[8].visible = true
                            //             scene.children[9].visible = true
                            //             scene.children[10].visible = true
                            //         }
                            //         if (rsqState[2] == 1) {
                            //             scene.children[11].visible = false
                            //             scene.children[12].visible = false
                            //             scene.children[13].visible = false
                            //             scene.children[14].visible = false

                            //         } else {
                            //             scene.children[11].visible = true
                            //             scene.children[12].visible = true
                            //             scene.children[13].visible = true
                            //             scene.children[14].visible = true
                            //         }
                            //         if (rsqState[3] == 1) {
                            //             scene.children[15].visible = false
                            //             scene.children[16].visible = false
                            //             scene.children[17].visible = false
                            //             scene.children[18].visible = false
                            //         } else {
                            //             scene.children[15].visible = true
                            //             scene.children[16].visible = true
                            //             scene.children[17].visible = true
                            //             scene.children[18].visible = true
                            //         }
                            //     }

                            // })
                        })
                    }
                } else {
                    const exit3D = () => {
                        mesh.children.forEach(item => {
                            console.log(item.type);
                            if (item.type == "Mesh") {
                                item.geometry.dispose()
                                item.material.map ? item.material.map.dispose() : ""
                                item.material.dispose()
                            }
                        });
                        scene.remove(mesh)
                    }

                    function closeDiag() {
                        scene ? (exit3D(), scene = light = spotLight = renderer = controls = camera = null) : ''
                        timer ? clearInterval(timer) : ""
                        oTodayTimer ? clearInterval(oTodayTimer) : ""
                        window.removeEventListener('resize', onWindowResize);

                    }
                    switch (i) {
                        case 0:
                            closeDiag()
                            setTimeout(() => {
                                window.location.href = "/index.html"
                            }, 200)
                            break;
                        case 1:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("全炉膛温度场", 11, "SJDL_IFS_DATA.prj", "全炉膛温度场")
                                window.location.href = "/quanlutang.html"
                            }, 200)

                            break;
                        case 2:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("横截面", 6, "SJDL_IFS_DATA.prj", "横截面")
                                window.location.href = "/hjm.html"
                            }, 200)

                            break;
                        case 3:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("燃烧稳定性监测", 7, "SJDL_IFS_DATA.prj", "燃烧稳定性监测")
                                window.location.href = "/ranshaowendingxing.html"
                            }, 200)

                            break;
                        case 4:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉分配率", 9, "SJDL_IFS_DATA.prj", "煤粉分配率")
                                window.location.href = "/meifen.html"
                            }, 200)

                            break;
                        case 5:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉颗粒度分布", 8, "SJDL_IFS_DATA.prj", "煤粉颗粒度分布")
                                window.location.href = "/main/dcimgs/gl/main.html"
                            }, 200)

                            break;
                        case 6:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警信息", 12, "SJDL_IFS_DATA.prj", "预警信息")
                                window.location.href = "/yujing.html"
                            }, 200)

                            break;
                        case 7:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("历史数据", 10, "SJDL_IFS_DATA.prj", "历史数据")
                                window.location.href = "/history.html"
                            }, 200)

                            break;
                        case 8:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警阈值配置修改", 14, "SJDL_IFS_DATA.prj", "预警阈值配置修改")
                                window.location.href = "/canshushezhi.html"
                            }, 200)

                            break;
                        default:

                    }

                }
            }
        }
    }

    let rsqState = ["", "", "", ""];
    document.getElementById('zbf_r_btns').addEventListener("click", function () {
        if (document.getElementById('zbf_r_btns').children[0].className == "active") {
            if (rsqState[0] == "1") {
                mesh.children[29].visible = false
            } else {
                mesh.children[29].visible = true
            }
        } else {
            mesh.children[29].visible = false
        }
        if (document.getElementById('zbf_r_btns').children[1].className == "active") {
            if (rsqState[1] == "1") {
                mesh.children[28].visible = false
            } else {
                mesh.children[28].visible = true
            }
        } else {
            mesh.children[28].visible = false
        }

        if (document.getElementById('zbf_r_btns').children[2].className == "active") {
            if (rsqState[2] == "1") {
                mesh.children[27].visible = false
            } else {
                mesh.children[27].visible = true
            }
        } else {
            mesh.children[27].visible = false
        }
        if (document.getElementById('zbf_r_btns').children[3].className == "active") {
            if (rsqState[3] == "1") {
                mesh.children[26].visible = false
            } else {
                mesh.children[26].visible = true
            }
        } else {
            mesh.children[26].visible = false

        }
    });
    initEvent('zbf_r_btns') //横截面温度分布 btns
    initEvent('zbf_foot_btns', true) //底部菜单 btns
    let oRBtns = document.getElementById("zbf_r_btns").children //底部菜单 btns
    let get3DFloorColorshishi = null

    // /**
    //  * 获取火焰点位
    //  * @param {string} pointName
    //  * @returns {number}
    //  */
    // function getFireIndex(pointName) {
    //     switch (pointName) {
    //         case 'A1':
    //             return 3;
    //         case 'A2':
    //             return 4;
    //         case 'A3':
    //             return 5;
    //         case 'A4':
    //             return 6;
    //         case 'B1':
    //             return 7;
    //         case 'B2':
    //             return 8;
    //         case 'B3':
    //             return 9;
    //         case 'B4':
    //             return 10;
    //         case 'C1':
    //             return 11;
    //         case 'C2':
    //             return 12;
    //         case 'C3':
    //             return 13;
    //         case 'C4':
    //             return 14;
    //         case 'D1':
    //             return 15;
    //         case 'D2':
    //             return 16;
    //         case 'D3':
    //             return 17;
    //         case 'D4':
    //             return 18;
    //         default:
    //             return 3;
    //     }
    // }
    
    async function fengceng() {
        // const databox = []
        const cengjibox = []
        const res = await request.get('/api/sjdl/home/dcs/zs').then(res => {
            // for (let k in res.data) { databox.push({ [k]: res.data[k] }) }
            for (let k in res.data) {
                // let index = 0;
                // if (scene && fireStateFlag) {
                //     console.log(scene);
                //     scene.children[getFireIndex(k)].visible = !(res.data[k] < 1200);
                // }
                cengjibox.push(res.data[k])
            }
            const databox = []
            for (let k in res.data) { databox.push({ [k]: res.data[k] }) }
            databox.sort((a, b) => {
                let aKey = Object.keys(a)[0];
                let bKey = Object.keys(b)[0];
                if (aKey[0] === bKey[0]) {
                    return aKey.slice(1) - bKey.slice(1);
                } else {
                    return aKey[0].charCodeAt() - bKey[0].charCodeAt();
                }
            });
            databox.forEach(obj => {
                let key = Object.keys(obj)[0];
                let value = obj[key].toFixed(2);
            })
            if (document.getElementById('zbf_r_btns').children[5].className == "") {
                for (let ahuo = 3; ahuo <= 18; ahuo++) {
                    scene.children[ahuo].visible = false
                }
            } else {
                databox.forEach((obj, index) => {
                    Object.keys(obj).forEach((key) => {
                        let value = obj[key];
                        if (value !== 0) {
                            scene.children[index + 3].visible = true
                        } else {
                            console.log(index + 3)
                            scene.children[index + 3].visible = false
                        }
                    });
                });
            }
        })

        // databox.sort((a, b) => {
        //     let aKey = Object.keys(a)[0];
        //     let bKey = Object.keys(b)[0];
        //     if (aKey[0] === bKey[0]) {
        //         return aKey.slice(1) - bKey.slice(1);
        //     } else {
        //         return aKey[0].charCodeAt() - bKey[0].charCodeAt();
        //     }
        // });
        // databox.forEach(obj => {
        //     let key = Object.keys(obj)[0];
        //     let value = obj[key].toFixed(2);
        // })
        const bool = cengjibox.every(item => item === 0.0)
        if (bool !== true) {
            mesh.children[7].material = runcaizhi
        } else {
            mesh.children[7].material = stopcaizhi
        }
        // databox.forEach((obj, index) => {
        //     Object.keys(obj).forEach((key) => {
        //         let value = obj[key];
        //         if (value !== 0) {
        //             scene.children[index + 3].visible = true
        //         } else {
        //             scene.children[index + 3].visible = false
        //         }
        //     });
        // });
    }
    const get3DFloorColor = () => {
        clearInterval(get3DFloorColorshishi)
        fengceng()
        request.post('/spf/visit/getThermalFieldAll').then(res => {
            // console.log(res.result)
            // rsqState[0] = res.data.runStateA
            // rsqState[1] = res.data.runStateB
            // rsqState[2] = res.data.runStateC
            // rsqState[3] = res.data.runStateD
            // // 判断有几层燃烧器横截面渲染火焰
            // if (document.getElementById('zbf_r_btns').children[0].className == "active") {
            //     // console.log(rsqState[0] == "1")
            //     if (rsqState[0] == "1") {
            //         mesh.children[29].visible = false
            //     } else {
            //         mesh.children[29].visible = true
            //     }
            // } else {
            //     mesh.children[29].visible = false
            // }
            // if (document.getElementById('zbf_r_btns').children[1].className == "active") {
            //     if (rsqState[1] == "1") {
            //         mesh.children[28].visible = false
            //     } else {
            //         mesh.children[28].visible = true
            //     }
            // } else {
            //     mesh.children[28].visible = false
            // }

            // if (document.getElementById('zbf_r_btns').children[2].className == "active") {
            //     if (rsqState[2] == "1") {
            //         mesh.children[27].visible = false
            //     } else {
            //         mesh.children[27].visible = true
            //     }
            // } else {
            //     mesh.children[27].visible = false
            // }
            // if (document.getElementById('zbf_r_btns').children[3].className == "active") {
            //     if (rsqState[3] == "1") {
            //         mesh.children[26].visible = false
            //     } else {
            //         mesh.children[26].visible = true
            //     }
            // } else {
            //     mesh.children[26].visible = false
            // }
            // for (const key in res.data) {
            //     // console.log(key.indexOf('runState'))
            //     if (key.indexOf('runState') == 0) {

            //     }
            // }
            res.code == 200 && res.data && set3DFloorColor(res.data)
            // setData(res.result)
            // res.result && res.result.dataList && res.result.dataList.length > 0 && initEventList(res.result.dataList)
            get3DFloorColorshishi = setInterval(() => { get3DFloorColor() }, 2500)
            removeLoader('加载中....')
        })
    }
    // {"code":"200","message":"成功",
    // "result":{"runStateA":0,"centerTempSOFA":1475.56,"centerTempE":1684.98,"centerTempD":1636.195,"runStateE":0,"centerTempC":1742.2875000000001,"runStateD":0,"centerTempB":1814.58,"runStateC":0,"centerTempA":1813.02,"runStateB":0}}
    const set3DFloorColor = (obj) => {
        // 12-17 sofa -a 操作透明度 停磨需隐藏
        // 18-23  sofa -a 蓝色风  停磨需隐藏
        let nameArr = ["A", "B", "C", "D", "SOFA"]
        for (let index = 0; index < nameArr.length; index++) {
            const element = nameArr[index];
            if (obj[`runState${nameArr[index]}`] == 1) {

            } else {
                let newTemp = obj[`centerTemp${nameArr[index]}`] > 1800 ? 1800 : obj[`centerTemp${nameArr[index]}`] < 1500 ? 1500 : obj[`centerTemp${nameArr[index]}`]
                scene.children[2].children[17 - index].material.opacity = newTemp == 0 ? 1 : ((1800 - newTemp) / 300).toFixed(2)
                // if (oRBtns[index].className == "active") {
                //     index == 5 ? "" : scene.children[2].children[23 - index].visible = true
                //     mesh.children[23].visible = false
                //     mesh.children[15].visible = false
                //     mesh.children[14].visible = false
                //     mesh.children[13].visible = false
                //     mesh.children[12].visible = false
                // }
                // console.log(scene.children[2].children[17-index].name,scene.children[2].children[17].material.opacity,newTemp);
            }

        }


    }
    // let c_form = eval('formview_' + now_open_diag.fmname)
    // c_form.onready = function () { // 页面打开 数据加载完成
    //     // initDataFromINnput()
    //     get3DFloorColor()
    // }
    lsLoader('加载中....')
    let timer = setInterval(() => {
        get3DFloorColor()
        clearInterval(timer)
    }, 500)
    let oTodayTimer = setInterval(() => {
        document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    }, 1000)
})()
